﻿
<style>


    #ele-canvas {
        border: 1px solid #5ea6ef;
    }

    .ele-control {
        /*margin-top: 30px;*/
        padding: 30px;
    }

    #page-input {
        width: 7%;
    }
</style>

<div id="app" v-loading.fullscreen.lock="fullscreenLoading" :element-loading-text="loadingText" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)">

    <div class="row">
        <div class="col-md-2">
            <div style="padding:10px;font-size:8px">
                <h3>当前签章信息</h3>
                <table class="table table-bordered">
                    <tr class="info">
                        <td>页码</td>
                        <td>签章方</td>
                        <td>签章坐标x,y</td>
                        <td>动作</td>
                    </tr>
                    <tr class="" v-for="item in signData">
                        <td>{{ item.pageIndex }}</td>
                        <td>{{ ['甲方','乙方','丙方','丁方','戊方'][item.contractPartys] }}</td>
                        <td>{{  parseInt(item.posX) }} , {{ parseInt(item.posY) }} </td>
                        <td>{{ item.sealType ==1?'负责人签字':item.sealType ==2?'主体盖章':item.sealType ==3?'盖章人签字':'其他' }}</td>
                    </tr>
                </table>
            </div>
        </div>

        <div class="col-md-5">

            <div style="padding:10px">
                <h3>合同信息 {{ viewData.onlyRead?'(只读模式)':'' }}</h3>
                <table class="table table-bordered">
                    <tr>
                        <td class="info">
                            合同编号
                        </td>
                        <td colspan="2">
                            {{ viewData.contractId }}
                        </td>
                    </tr>
                    <tr>
                        <td class="info">
                            合同名称
                        </td>
                        <td colspan="2">
                            {{ viewData.contractName }}
                        </td>
                    </tr>
                    <tr class="info">
                        <td>签章方</td>
                        <td>公司名</td>
                        <td>添加签章</td>
                    </tr>
                    <tr class="" v-for="item in viewData.contractPartysInfos">
                        <td>{{ ['甲方','乙方','丙方','丁方','戊方'][item.contractPartys] }} ({{ item.signatureType }}) </td>
                        <td>{{ item.vendorName }}</td>
                        <td>
                            <el-button-group>
                                <el-button v-if="item.signatureType!='个人'" size="mini" :disabled="viewData.onlyRead" type="primary" v-on:click="addNewSign(item.contractPartys, 2)">{{ item.signatureType=='个人'?'个人':'企业' }}盖章</el-button>
                                <el-button size="mini" :disabled="viewData.onlyRead" type="primary" v-on:click="addNewSign(item.contractPartys, 3)">{{ item.signatureType=='个人'?'个人':'盖章人' }}签字</el-button>
                                <el-button v-if="item.partyPrimeSignature && item.signatureType!='个人'" size="mini" :disabled="viewData.onlyRead" type="primary" v-on:click="addNewSign(item.contractPartys, 1)">{{ item.partyPrimeSignature }} 签字</el-button>
                            </el-button-group>
                        </td>
                    </tr>
                </table>
            </div>


            <div class="ele-control">
                <button :disabled="viewData.onlyRead" type="button" class="btn btn-default" v-on:click="removeSignature">删除当前签章</button>
                <button :disabled="viewData.onlyRead" type="button" class="btn btn-danger" v-on:click="clearSignature">清除此页所有签章</button>
                <button :disabled="viewData.onlyRead" type="button" class="btn btn-success" v-on:click="closeWin">保存并确认盖章位置</button>

                @*<button v-on:click="debugTest">debug</button>*@

                @*<button v-on:click="confirmSignature">确定当前签章位置</button>
                    <button v-on:click="submitSignature">提交所有签章信息</button>*@
            </div>
            @*{{ viewData }}*@
        </div>



        <div class="col-md-5 elesign">
            <!-- pdf的预览 -->
            <div class="center">
                <div>
                    <el-button-group>
                        <el-button size="mini" type="primary" icon="el-icon-arrow-left" v-on:click="prevPage">上一页</el-button>
                        <el-button size="mini" type="primary" v-on:click="nextPage">下一页<i class="el-icon-arrow-right el-icon--right"></i></el-button>
                    </el-button-group>
                    <el-select v-model="pageNum" size="mini">
                        <el-option v-for="page in totalPageNum"
                                   :key="page"
                                   :label="page + '/' + totalPageNum + '页'"
                                   :value="page">
                            <span style="float: left">{{ page }}</span>
                            <span style="float: right; color: #8492a6; font-size: 13px">{{  pageDesc(page) }}</span>
                        </el-option>
                    </el-select>

                </div>
                <canvas id="the-canvas" />
            </div>

            <!-- 盖章部分 -->
            <canvas id="ele-canvas"></canvas>
        </div>



    </div>
</div>


<script>
    let pdfjsLib = window["pdfjs-dist/build/pdf"];
    //console.log('pdfjsLib', pdfjsLib)
    pdfjsLib.GlobalWorkerOptions.workerSrc = `http://${window.location.host}/pdf.worker.js`;

    let storage = window.localStorage;
    var app = new Vue({
        el: '#app',
        components: {

        },
        data() {
            return {
                pdfUrl: '',
                pdfDoc: null,
                pageNum: 1,
                totalPageNum:1,
                scale: 1,
                pageRendering: false,
                pageNumPending: null,
                //sealUrl: '',
                //signUrl: '',
                canvas: null,
                ctx: null,
                canvasEle: null,
                whDatas: null,

                currentObj: {}, //当前拖拽对象
                viewData: {},
                signData: [],   // 拷贝原始数据而来，后续修改不动原始数据，方便提供还原功能
                fullscreenLoading: false,
                loadingText: '',
            };
        },

        //计算属性,就是依赖其它的属性计算所得出最后的值
        computed: {
            hasSigna() {
                return !!this.canvasEle && !!this.canvasEle.getObjects()[0] ? true : false;
            },
        
        },

        watch: {
            whDatas: {
                handler() {
                    if (!!this.whDatas) {
                        this.renderFabric();
                        this.canvasEvents();
                    }
                },
            },

            pdfUrl: function (val) {
                this.$nextTick(() => {
                    this.showpdf(val);
                });
            },
            pageNum: function (pageNum) {
                pageNum = Number(pageNum);
                if (pageNum < 1) {
                    this.pageNum = 1;
                    return;
                }
                if (pageNum >= this.pdfDoc.numPages) {
                    this.pageNum = this.pdfDoc.numPages;
                }
                if (!(/(^[1-9]\d*$)/.test(pageNum))) {
                    this.pageNum = 1;
                    return;
                }

                if (pageNum >= 1 && pageNum <= this.pdfDoc.numPages) {
                    this.commonSign(pageNum);
                    this.queueRenderPage(pageNum);
                } 
            },

        },

        methods: {
            pageDesc(page) {
                let index = this.signData.findIndex(it => it.pageIndex == page);
                if (index >= 0) {
                    return "签章页";
                }
                return "";
            },

            // 关闭页面并回传数据
            closeWin() {
                if (confirm("确认保存修改？将关闭当前页面\n\n请确认！") == true) {
                    if (window.opener) {
                        window.opener.postMessage({ 'type': 'signData', message: JSON.stringify(this.signData) }, '*');
                        window.close();
                    }
                }
            },

            debugTest() {
                console.log('debugTest', this._data)
                let signData = this.canvasEle.getObjects();
                console.log('signData', signData)
            },
            renderPage(num) {
                let _this = this;
                this.pageRendering = true;
                // Using promise to fetch the page
                return this.pdfDoc.getPage(num).then((page) => {
                    let viewport = page.getViewport({ scale: _this.scale });
                    _this.canvas.height = viewport.height;
                    _this.canvas.width = viewport.width;

                    // Render PDF page into canvas context
                    let renderContext = {
                        canvasContext: _this.ctx,
                        viewport: viewport,
                    };
                    let renderTask = page.render(renderContext);

                    // Wait for rendering to finish
                    renderTask.promise.then(() => {
                        _this.pageRendering = false;
                        if (_this.pageNumPending !== null) {
                            // New page rendering is pending
                            this.renderPage(_this.pageNumPending);
                            _this.pageNumPending = null;
                        }
                    });
                });
            },
            queueRenderPage(num) {
                if (this.pageRendering) {
                    this.pageNumPending = num;
                } else {
                    this.renderPage(num);
                }
            },
            prevPage() {

                if (this.pageNum <= 1) {
                    return;
                }
                this.pageNum--;
            },
            nextPage() {
                if (this.pageNum >= this.pdfDoc.numPages) {
                    return;
                }
                this.pageNum++;
            },
            showpdf(pdfUrl) {
                this.canvas = document.getElementById("the-canvas");
                this.ctx = this.canvas.getContext("2d");

                pdfjsLib.getDocument(pdfUrl).promise.then((pdfDoc_) => {
                    this.pdfDoc = pdfDoc_;
                    //document.getElementById("page_count").textContent = this.pdfDoc.numPages;
                    this.totalPageNum = this.pdfDoc.numPages;
                    this.renderPage(this.pageNum).then((res) => {
                        this.renderPdf({
                            width: this.canvas.width,
                            height: this.canvas.height,
                        });
                    });
                    this.commonSign(this.pageNum, true);
                });
            },


            // 设置绘图区域宽高
            renderPdf(data) {
                this.whDatas = data;
                // console.log(data)
                document.querySelector(".elesign").style.width = data.width + "px";
            },

            // 生成绘图区域
            renderFabric() {
                let canvaEle = document.querySelector("#ele-canvas");

                canvaEle.width = this.whDatas.width;
                canvaEle.height = this.whDatas.height;

                this.canvasEle = new fabric.Canvas(canvaEle);
                let container = document.querySelector(".canvas-container");
                container.style.position = "absolute";
                container.style.top = "42px";
            },

            // 相关事件操作
            canvasEvents() {
                // 拖拽边界 不能将图片拖拽到绘图区域外
                this.canvasEle.on("object:moving", function (e) {
              
                    var obj = e.target;
                    // if object is too big ignore
                    if (obj.currentHeight > obj.canvas.height || obj.currentWidth > obj.canvas.width) {
                        return;
                    }
           
                    obj.setCoords();
                    // top-left  corner
                    if (obj.getBoundingRect().top < 0 || obj.getBoundingRect().left < 0) {
                        obj.top = Math.max(obj.top, obj.top - obj.getBoundingRect().top);
                        obj.left = Math.max(obj.left, obj.left - obj.getBoundingRect().left);
                    }
                    // bot-right corner
                    if (obj.getBoundingRect().top + obj.getBoundingRect().height > obj.canvas.height || obj.getBoundingRect().left + obj.getBoundingRect().width > obj.canvas.width) {
                        obj.top = Math.min(obj.top, obj.canvas.height - obj.getBoundingRect().height + obj.top - obj.getBoundingRect().top);
                        obj.left = Math.min(obj.left, obj.canvas.width - obj.getBoundingRect().width + obj.left - obj.getBoundingRect().left);
                    }
                });
                // 拖拽完毕后更新数据
                this.canvasEle.on('object:modified', () => {
                    this.updateToView()
                });

            },

            // 同步更新当前页的签章数据到数据里
            updateToView() {
                if (this.canvasEle == null) {
                    return;
                }
                console.log('updateToView')

                let _t = this.signData
                let data = this.canvasEle.getObjects(); //获取当前页面内的所有签章信息
                console.log('updateToView this.data', data)

                console.log('updateToView this.pageNum', this.pageNum)
                // 删除当前页码的签章再更新
                for (let i = _t.length - 1; i >= 0; i--) {
                    if (_t[i].pageIndex == this.pageNum) {
                        console.log('del ', _t[i])

                        _t.splice(i, 1);
                    }
                }

                for (let val of data) {
                    let sign = {
                        contractPartys: val.signData.contractPartys,
                        keyWord: val.signData.keyWord,
                        pageIndex: val.signData.pageIndex,
                        signMode: val.signData.signMode,
                        sealType: val.signData.sealType,
                        posX: val.left,
                        posY: val.top
                    }
                    console.log('push', sign)
                    _t.push(sign)
                }
                _t.sort((a, b) => {
                    return a.pageIndex - b.pageIndex;
                });
                this.signData = _t;

            },
            // 页码刷新签章（原有的数据）
            addSign(item, left = 0, top = 0, updateView = true) {
                let onlyRead = this.viewData.onlyRead
                let signUrl = '/signature_' + item.contractPartys + ".png"
                if (item.sealType == 1 ) {
                    signUrl = '/signature_' + item.contractPartys + "_u.png"
                }
                if ( item.sealType == 3) {
                    signUrl = '/signature_' + item.contractPartys + "_u2.png"
                }
                fabric.Image.fromURL(
                    signUrl,
                    (oImg) => {
                        oImg.set({
                            signData: item, // 这里注入签章数据
                            hasControls: false,
                            left: left,
                            top: top,
                            width: 160,
                            height: 180,
                            // angle: 10,
                            scaleX: 0.6,
                            scaleY: 0.6,
                            lockMovementX: onlyRead,
                            lockMovementY: onlyRead

                        });
                        //oImg.scale(0.5); //图片缩小一半
                        this.canvasEle.add(oImg);
                    }
                );
                if (updateView) {
                    this.updateToView();
                }
            },
            // 手动添加新的盖章
            addNewSign(contractPartys, sealType) {
                let type = (sealType == 1 || sealType == 3)?'签字':'盖章'
                let item = {
                    contractPartys: contractPartys,
                    keyWord: ['甲方', '乙方', '丙方', '丁方', '戊方'][contractPartys] + type,
                    pageIndex: this.pageNum,
                    posX: 0,
                    posY: 0,
                    signMode: 1,
                    sealType: sealType
                }
                this.addSign(item)
                let index = this.signData.findIndex(it => it.pageIndex == this.pageNum)
                this.signData.splice(index, 0, item);
            },

            // 删除签章
            removeSignature() {
                this.canvasEle.remove(this.canvasEle.getActiveObject())
                this.updateToView();
            },

            //翻页展示盖章信息
            commonSign(pageNum, isFirst = false) {
                if (isFirst == false) this.canvasEle.remove(this.canvasEle.clear()); //清空页面所有签章

                for (let i = 0; i < this.signData.length; i++) {
                    let sign = this.signData[i];
                    if (pageNum == sign.pageIndex) {
                        console.log('pageNum', pageNum)
                        console.log('addSign', sign)
                        this.addSign(sign, sign.posX, sign.posY, false)
                    }
                }
            },


            //清除当前页面签章数据
            clearSignature() {
                if (confirm("确认清除当前页码所有签章？\n\n请确认！") == true) {
                    this.canvasEle.remove(this.canvasEle.clear()); //清空页面所有签章
                    this.updateToView();
                }
            },

            getSignatureDataBySessionId(sessionId) {

                this.fullscreenLoading = true;
                this.loadingText = '正在加载PDF文件信息,请稍后...'
                axios.get('/GetSignatureDataBySessionId?sessionId=' + sessionId)
                    .then(res => {
                        if (res.data.succeed) {
                            this.fullscreenLoading = false;
                            let data = res.data.data
                            this.pdfUrl = data.pdfPath
                            this.viewData = data
                            this.signData = data.signatures;

                            console.log('data', data)
                        } else {
                            alert(res.data.errMsg)
                            this.fullscreenLoading = false;
                        }
                    }).catch(err => {
                        alert('读取失败' + err.errMsg)

                        this.fullscreenLoading = false;
                    })
            },


            // 获取当前路由参数
            getQueryString(name) {
                var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
                var r = window.location.search.substr(1).match(reg);
                if(r != null) return decodeURI(r[2]);
                return null;  
            }
        },

        //未渲染html页面时执行
        created: function () {
            let sessionId = this.getQueryString('sessionId')
            if (sessionId) {
                this.getSignatureDataBySessionId(sessionId)
            } else {
                alert('未找到 sessionId')
            }



        },

        mounted() {



        }
    });

</script>

<script>

 

</script>